class WxH5Authorize {
  // 存储上一次授权的时间
  AUTHORIZE_TIME = 'AUTHORIZE_TIMING_20201022';

  // 30s内的授权code记为有效
  AUTHORIZE_DURATION = 300000;

  checkAuthorizeLocal () {
    var times = parseInt(localStorage.getItem(this.AUTHORIZE_TIME))
    if (times) {
      return new Date().getTime() - times < this.AUTHORIZE_DURATION
    } else {
      return false
    }
  }

  authorize () {
    var host = window.location.host
    var pathname = window.location.pathname
    if (pathname !== '/pages/pdf/test-paper/index') {
      if (host === 'm.bendiclass.com' || host === 'test-m.bendiclass.com') {
        var code = this.getQuery('code')
        if (!code) {
          this.forWard()
        } else if (this.checkAuthorizeLocal()) {
          localStorage.setItem('wxCode', code)
          localStorage.removeItem(this.AUTHORIZE_TIME)
        } else {
          this.forWard()
        }
      }
    }
  }

  forWard () {
    localStorage.setItem(this.AUTHORIZE_TIME, JSON.stringify(new Date().getTime()))
    window.location.href = this.getCode()
  }

  getCode () {
    var BaseUrl = encodeURIComponent(this.getAuthorizeUrl())
    return 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx6223f311b532c11d&redirect_uri=' + BaseUrl + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
  }

  getAuthorizeUrl () {
    var href = window.location.href
    var search = window.location.search
    if (~search.indexOf('code')) {
      var query = this.params2json(search.slice(1))
      delete query.code
      delete query.mainUserId
      return window.location.origin + window.location.pathname + '?' + this.json2params(query) + '&isSharedPage=1'
    } else {
      return href
    }
  }

  getQuery (name) {
    var reg = new RegExp('(\\?|&)' + name + '=([^&]*)(&|$)', 'i')
    var m = window.location.search.match(reg)
    return m && m.length > 2 ? decodeURIComponent(m[2]) : ''
  }

  params2json (params, slice) {
    params = params || ''
    slice = slice || '&'
    var result = {}
    params.split(slice).forEach(function (item) {
      var arr = item.split('=')
      var key = arr[0] || ''
      var value = arr[1] || ''
      if (item && key) {
        result[key] = value
      }
    })
    return result
  }

  json2params (json, slice) {
    json = json || {}
    slice = slice || '&'
    return Object.keys(json).reduce(function (acc, item) {
      return acc + '' + item + '=' + json[item] + slice
    }, '').slice(0, -1)
  }
}

export default new WxH5Authorize()
